import 'dart:async';

import 'package:get/get.dart';
import 'package:winkai/db/dao/ses_dao.dart';
import 'package:winkai/db/db_ext.dart';
import 'package:winkai/entity/role_info.dart';
import 'package:winkai/helper/iap/iap_helper.dart';
import 'package:winkai/helper/service_conf_helper.dart';
import 'package:winkai/helper/ses_helper.dart';
import 'package:winkai/helper/user_helper.dart';
import 'package:winkai/helper/value_helper.dart';
import 'package:winkai/main.dart';
import 'package:winkai/route/route_manifest.dart';
import 'package:winkai/ui/msg/controller/msg_controller.dart';
import 'package:winkai/ui/user/dialog/edit_name_dialog.dart';

import '../service/ses_service.dart';

class ChatHelper {
  static ChatHelper? _singleton;

  factory ChatHelper() {
    _singleton ??= ChatHelper._();
    return _singleton!;
  }

  ChatHelper._();

  void jumpToChatPage(RoleInfo roleInfo) async {
    var isSetNickname = await _checkIsSetNickname();
    if (isSetNickname) {
      var sessionId = genSessionId(aiRoleInfo: roleInfo);
      await getIt<SesService>().createSession(sessionId);
      var sessionInfo = await getIt<SesService>().selectSingleOrNull(sessionId);
      SesInfo? currentSession;
      try {
        currentSession = Get.find<MsgController>()
            .sessionList
            .firstWhereOrNull((element) => element.session.id == sessionId);
      } catch (e) {}
      UserHelper().subtract(
          currentSession?.unreadCount ?? sessionInfo?.session.unReadNum ?? 0);
      if (sessionInfo != null) {
        SesHelper().stack.push(sessionInfo);
        getIt<SesService>().resetUnReadNum(sessionId);
        jump() async {
          try {
            await Get.toNamed(
              RouteManifest.chatPage,
              arguments: {
                'sessionId': sessionId,
                'roleInfo': roleInfo,
              },
            );
            SesHelper().stack.pop();
            return;
          } catch (e) {
            SesHelper().stack.pop();
            rethrow;
          }
        }

        jump();
      }
    }
  }

  Future<bool> _checkIsSetNickname() async {
    Completer<bool> completer = Completer();
    if (UserHelper().user.nickname?.isNotEmpty == true) {
      return true;
    } else {
      var context = Get.context;
      if (context == null) return false;
      showNameDialog(
        context,
        onComplete: () {
          if (!completer.isCompleted) {
            completer.complete(true);
          }
        },
      );
    }
    return completer.future;
  }

  ///是否需要订阅
  bool isNeedSubscribe() {
    if (!ServiceConfHelper().isFreeChatMode &&
        !IAPHelper().isVip &&
        ValueHelper.instance.sendFreeMessageCount >
            ServiceConfHelper().freeMessageCount) {
      return true;
    }
    return false;
  }

  ///记录发送免费消息的数量
  void addSendFreeMsgCount() {
    if (!IAPHelper().isVip) {
      ValueHelper.instance.addSendFreeMessageCount();
    }
  }
}
